#include "../header.h"

//多用登录 - 并发服务器 -fork

int main(int argc, char const *argv[])
{
    if(argc < 3)
    {
        perror("usage:./server ip port\n");
        return -1;
    }

    //.建立套接字
    int sid = socket(AF_INET,SOCK_STREAM,0);
    printf("sid = %d\n",sid);

    //实际地址结构体
    struct sockaddr_in saddr = {0};
    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = inet_addr(argv[1]);    
    saddr.sin_port = htons(atoi(argv[2]));
    if(bind(sid,(struct sockaddr*)&saddr,sizeof(saddr))<0)
    {
        perror("bind error\n");
        return -2;
    }
    printf("bind successful\n");

    //3.监听
    listen(sid,10);
    int cid = -1;
    pid_t pid = -2;
    //4.循环连接
    char bufs[128] = "";
    int len = 0 ;
    while (1)
    {
        cid = accept(sid,NULL,NULL);
        if(cid == -1)
        {
            perror("accept error\n");
            return -2;
        }
        printf("有新用户登录 cid = %d\n",cid);
        pid =  fork(); 
        if(pid < 0 )
            exit(-2);
        if(pid == 0)  //子进程负责读写
        {
            //循环反弹数据。
            while(1)
            {
                bzero(bufs,sizeof(bufs));
                //本服务器实现的反弹数据的功能
                len =  recv(cid,bufs,sizeof(bufs),0);
                if(!strncmp(bufs,"quit",4))
                {
                    printf("客户端正在退出!\n");
                    break;
                }
                printf("从客户端接收到的数据是:%s\n",bufs);
                send(cid,bufs,strlen(bufs),0);
            }
             //退出以后 关闭。
            shutdown(cid,SHUT_RDWR);
            //子进程退出。
            exit(0);
        }

    }
    



    return 0;
}
